//
//  QJPreviewOrderVC.m
//  QuanJieShopProject
//
//  Created by 刘中义 on 2018/2/19.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJPreviewOrderDetailVC.h"
#import "QJPreviewOrderVCHeaderView.h"
#import "QJPreviewOrderCell.h"
#import "QJPreviewOrderVCFooterView.h"
#import "QJOrderPayVC.h"
#import "QJMineAddressVC.h"
#import "QJPointPayVC.h"
// 预览订单
@interface QJPreviewOrderDetailVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *previewTableView;
@property (nonatomic, strong) QJPreviewOrderVCHeaderView *orderHeaderView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) QJPreviewOrderVCFooterView *orderFooterView;
@property (nonatomic, strong) NSString *addressStr;
@property (nonatomic, strong) NSMutableDictionary *changeDic;
@end

@implementation QJPreviewOrderDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUIAction];
    [self dataRequestAction];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addressSelectedNotification:) name:@"addressSelectedNotification" object:nil];
}
- (void)addressSelectedNotification:(NSNotification *)noti{
    self.addressStr = noti.object;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated]; 
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
#pragma mark -- 界面布局方法
- (void)setupUIAction{
    WEAKSELF
    self.title = @"订单详情";
    self.orderHeaderView = [[[NSBundle mainBundle]loadNibNamed:@"QJPreviewOrderVCHeaderView" owner:self options:nil] lastObject];
    self.orderHeaderView.frame = CGRectMake(0, 0, UISCREEN_WIDTH, 80);
    
    
    self.orderFooterView = [[[NSBundle mainBundle]loadNibNamed:@"QJPreviewOrderVCFooterView" owner:self options:nil]firstObject];
    self.orderFooterView.frame = CGRectMake(0, 0, UISCREEN_WIDTH, 100);
    self.orderFooterView.uploadOrderBlcok = ^{
        //提交订单
        [weakSelf uploadOrderAction];
    };
    
    self.previewTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, UISCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.previewTableView];
    self.previewTableView.delegate = self;
    self.previewTableView.dataSource = self;
    self.previewTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.previewTableView.tableHeaderView = self.orderHeaderView;
    self.previewTableView.backgroundColor = HexRGB(0xe6e6e6);
    self.previewTableView.tableFooterView = self.orderFooterView;
    
    self.addressStr = @"";
    
}
#pragma mark -- 数据请求方法
- (void)dataRequestAction{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if ([self.orderType isEqualToString:@"1"]) {  // 购物车结算
        
        
        
    }else{ // 商品详情结算
        [dict setObject:self.orderGoodsid forKey:@"goods_id"];
        [dict setObject:self.amountStr forKey:@"goods_num"];
        [dict setObject:self.specificationsString forKey:@"item_id"];
        [dict setObject:@"buy_now" forKey:@"action"];
    }

    NSLog(@"订单预览 dict = %@", dict);
    [WWNetRequest fetchOrderInfoWithParameters:dict success:^(id response) {

         NSLog(@"订单预览 response = %@", response);
        if ([response isKindOfClass:[NSDictionary class]]) {
            WEAKSELF
            [weakSelf.orderHeaderView headerUpdateDataWithDic:response[@"data"]];
            [weakSelf.orderFooterView footerUpdateDataWithDic:response[@"data"][@"cartPriceInfo"]];

            weakSelf.changeDic = [NSMutableDictionary dictionaryWithDictionary:response];
            
            NSArray *shopArr = response[@"data"][@"cartList"];
            NSMutableArray *tempArr = [NSMutableArray array];
            for (NSDictionary *shopDict in shopArr) {
                NSArray *goodsArr = shopDict[@"cart_list"];
                
                for (NSDictionary *goodsDict in goodsArr) {
                    PreviewOrderModel *model = [[PreviewOrderModel alloc]initWithDictionary:goodsDict error:nil];
                    model.image_url = goodsDict[@"goods"][@"original_img"];
                    [tempArr addObject:model];
                }
            }
            self.dataArray = tempArr;
            [self.previewTableView reloadData];
            
            NSDictionary *address = response[@"data"][@"address"];
            if ([address isKindOfClass:[NSDictionary class]]) {
                self.addressStr = [NSString stringWithFormat:@"%@",address[@"address_id"]];
            }else{
                self.addressStr = @"";
            }
        }
    } failure:^(NSDictionary *error) {
        NSLog(@"订单预览 error = %@", error);

    }];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    QJPreviewOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QJPreviewOrderCell" owner:self options:nil] lastObject];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PreviewOrderModel *model = self.dataArray[indexPath.row];
    [cell cellUpdateWithModel:model];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
      PreviewOrderModel *model = self.dataArray[indexPath.row];
//    if (self.cellDidSelectedBlock) {
//        self.cellDidSelectedBlock(model);
//    }
    
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
#pragma mark -- 提交订单方法
- (void)uploadOrderAction{
    
    if (self.addressStr.length < 1) {
        [MBPHUD showAlertWithTitle:@"请选择收货地址!"];
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if ([self.orderType isEqualToString:@"1"]) {  // 购物车
        [dict setObject:@"submit_order" forKey:@"act"];  // 订单id
        [dict setObject:self.addressStr forKey:@"address_id"];
        
    }else{ // 商品详情(有规格,无规格)
        [dict setObject:self.addressStr forKey:@"address_id"];
        [dict setObject:self.amountStr forKey:@"goods_num"];
        [dict setObject:self.specificationsString forKey:@"item_id"];
        [dict setObject:@"" forKey:@"payPwd"];
        [dict setObject:self.orderGoodsid forKey:@"goods_id"];
        [dict setObject:@"buy_now" forKey:@"action"];
         [dict setObject:@"submit_order" forKey:@"act"];
    }

    NSLog(@"提交订单dict = %@", dict);
    [WWNetRequest fetchCreateOrderWithParameters:dict success:^(id response) {
        
        NSLog(@"提交订单 response = %@", response);
        if ([response isKindOfClass:[NSDictionary class]]) {
            NSString *orderStr = [NSString stringWithFormat:@"%@",response[@"data"][@"order_id"]];
            NSDictionary *dic = response[@"data"][@"other"];
            NSDictionary *userAmongDic = [dic objectForKey:@"user_among_arr"];
        //需判断是从商品详情还是从购物车结算
        //需判断是普通商品还是积分商品
        if ([self.orderType isEqualToString:@"2"]) {//商品详情支付
            
            if ([self.goodsType isEqualToString:@"积分商品"]) {
                
                QJPointPayVC  *VC = [[QJPointPayVC alloc]init];
                VC.payOrderStr = orderStr;
                
                VC.silverAmount = [userAmongDic objectForKey:@"silver_ye"];
                VC.pointsAmount = [userAmongDic objectForKey:@"balance_user_integral"];
                VC.totalAmountStr = response[@"data"][@"other"][@"total_amount"];
                KPushViewControllerAction(VC);
                
            }
            if (self.goodsType == nil) {//普通商品
               
                QJOrderPayVC  *VC = [[QJOrderPayVC alloc]init];
                VC.payOrderStr = orderStr;
                VC.yeAmount = [userAmongDic objectForKey:@"ye"];
                VC.silverAmount = [userAmongDic objectForKey:@"silver_ye"];
                VC.pointsAmount = [userAmongDic objectForKey:@"balance_user_integral"];
                VC.totalAmountStr = dic[@"total_amount"];
                KPushViewControllerAction(VC);
            }
            
        }
        if ([self.orderType isEqualToString:@"1"]) {//购物车支付
            
            if (self.goodsType == nil) {
                QJOrderPayVC  *VC = [[QJOrderPayVC alloc]init];
                VC.payOrderStr = orderStr;
                VC.yeAmount = [userAmongDic objectForKey:@"ye"];
                VC.silverAmount = [userAmongDic objectForKey:@"silver_ye"];
                //            VC.pointsAmount = [userAmongDic objectForKey:@"balance_user_integral"];
                VC.totalAmountStr = response[@"data"][@"other"][@"total_amount"];
                KPushViewControllerAction(VC);
          
            }
        }
       
        }
        
    } failure:^(NSDictionary *error) {
        NSLog(@"提交订单 error = %@", error);

    }];
}
#pragma mark -- 懒加载
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableDictionary *)changeDic{
    if (!_changeDic) {
        _changeDic = [NSMutableDictionary dictionary];
    }
    return _changeDic;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
